package com.springboot.jwt.config.token.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.springboot.dao.SystemMenuDao;
import com.springboot.dao.UserLoginDao;
import com.springboot.dao.UserLoginJwtDao;
import com.springboot.entity.UserLoginEntity;
import com.springboot.entity.UserLoginJwtEntity;
import com.springboot.jwt.config.token.JwtCheckToken;
import com.springboot.jwt.error.JwtException;
import com.springboot.type.SystemUserType;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Classname AdminJwtCheckToken
 * @Description 系统管理端token校验
 * @Version 1.0.0
 * @Date 2024/4/10 15:02
 * @Created by zyj
 */
@Component
@Slf4j
public class AdminJwtCheckToken implements JwtCheckToken {

    private String jwt_tishi = "token无效，请重新登录";

    @Resource
    private UserLoginDao userLoginDao;

    @Resource
    private SystemMenuDao systemMenuDao;

    @Resource
    private UserLoginJwtDao userLoginJwtDao;


    @Override
    public void checkToken(HttpServletRequest httpServletRequest, String token) throws JwtException {
        // 获取 token 中的 user id
        Integer userId;
        try {
            String userIds = JWT.decode(token).getAudience().get(0);
            if(StringUtils.isEmpty(userIds)){
                throw new JwtException(jwt_tishi);
            }
            log.info("checkJwt  userId:{}", userIds);
            userId = Integer.parseInt(userIds);
        } catch (JWTDecodeException e) {
            log.error("token获取用户信息失败", e);
            throw new JwtException(jwt_tishi);
        }

        UserLoginEntity user = userLoginDao.selectById(userId);
        if (user == null) {
            log.info("用户不存在");
            throw new JwtException(jwt_tishi);
        }

        /**验证用户是否有接口权限*/
        //不为超级管理员
        if (!SystemUserType.type_root.equals(user.getUserType())) {
            String requestURI = httpServletRequest.getRequestURI().replaceFirst("/+", "");

            //用户接口权限
            String interfaceUrl = systemMenuDao.getAuthMenuByUserId(user.getUserId());
            if (!interfaceUrl.contains(requestURI)) {
                throw new JwtException(JwtException.code_interface_error, JwtException.code_interface_error_msg);
            }
        }

        //校验数据库token
        Date nowDate = new Date();
        UserLoginJwtEntity userLoginJwtEntity = userLoginJwtDao.selectByJwtAndUserId(userId, token);
        if (ObjectUtils.isEmpty(userLoginJwtEntity)) {
            throw new JwtException(jwt_tishi);
        }
        if (nowDate.after(userLoginJwtEntity.getEndTime())) {
            throw new JwtException(jwt_tishi);
        }

        try {
            // 验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserPassword())).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            log.error("用户不存在", e);
            throw new JwtException(jwt_tishi);
        }

    }
}
